package com.yh.hljapp.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yh.hljapp.AppConfig;
import com.yh.hljapp.AppContext;
import com.yh.hljapp.R;
import com.yh.hljapp.api.ErrorHandler;
import com.yh.hljapp.api.RetrofitSingleton;
import com.yh.hljapp.base.BaseFragment;
import com.yh.hljapp.common.FullyLinearLayoutManager;
import com.yh.hljapp.common.MyScrollview;
import com.yh.hljapp.common.PLog;
import com.yh.hljapp.common.StringUtils;
import com.yh.hljapp.common.TDevice;
import com.yh.hljapp.common.UIHelper;
import com.yh.hljapp.gddb.gbmanager.AddSale_Manager;
import com.yh.hljapp.gddb.gdbean.AddSaleInt_bodyBean;
import com.yh.hljapp.gddb.gdbean.AddSaleInt_body_InOutList_Bean;
import com.yh.hljapp.gddb.gdbean.AddSaleOut_HeadBean;
import com.yh.hljapp.gddb.gdbean.Add_Sync_Bean;
import com.yh.hljapp.gddb.gdbean.Add_bodyOut_Bean;
import com.yh.hljapp.modules.adatper.Add_Saleout_Adapter;
import com.yh.hljapp.modules.bean.AddSaleOut_HB_Bean;
import com.yh.hljapp.modules.bean.CM;
import com.yh.hljapp.modules.bean.CustPhone;
import com.yh.hljapp.modules.bean.Result;
import com.yh.hljapp.modules.bean.SimpleBackPage;
import com.yh.hljapp.modules.bean.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static android.R.id.list;
import static android.content.Context.MODE_PRIVATE;
import static com.yh.hljapp.AppConfig.SCN_CUST_ACTION_SCODE;

/**
 * =========================
 * 版权所有，违法必究
 * 作者：zhanghang
 * <p>
 * 工程：hlj
 * <p>
 * 文件名：ADDSaleIntFragment
 * <p>
 * 创建时间：2017.07.31.11:40
 */

public class ADDSaleOutFragment extends BaseFragment implements Add_Saleout_Adapter.OnSaleAddAdapterListern {


    @InjectView(R.id.tv_gh_unit)
    TextView tvGhUnit;
    @InjectView(R.id.tv_all)
    TextView tv_all;
    @InjectView(R.id.ll_gh_unit)
    LinearLayout llGhUnit;
    @InjectView(R.id.tv_zdr)
    TextView tvZdr;
    @InjectView(R.id.ll_content)
    LinearLayout ll_content;
    @InjectView(R.id.ll_zdr)
    LinearLayout llZdr;
    @InjectView(R.id.tv_fh)
    TextView tvFh;
    @InjectView(R.id.ll_fh)
    LinearLayout llFh;
    @InjectView(R.id.tv_ywy)
    TextView tvYwy;
    @InjectView(R.id.ll_ywy)
    LinearLayout llYwy;
    @InjectView(R.id.tv_bg)
    TextView tvBg;
    @InjectView(R.id.ll_bg)
    LinearLayout llBg;
    @InjectView(R.id.tv_sh_warehouse)
    TextView tvShWarehouse;
    @InjectView(R.id.ll_sh_warehouse)
    LinearLayout llShWarehouse;
    @InjectView(R.id.recyclerview)
    RecyclerView mRecycleview;
    @InjectView(R.id.scrollView)
    MyScrollview scrollView;

    private Add_Saleout_Adapter mAdapter;
    ArrayList<Add_bodyOut_Bean> checkedCKS;
    private AddSaleOut_HeadBean addSaleOut_HeadBean;
    private int position;
    private boolean isSave;
    private String mType;
    private User mUser;
    private String currBillNumb;
    private int count;

    //    private List<String> mFbillNumberList = new ArrayList<>();
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    private BroadcastReceiver mSamDataReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(SCN_CUST_ACTION_SCODE)) {
                String message = intent.getStringExtra(AppConfig.SCN_CUST_EX_SCODE);
                JSONObject jo = null;
                try {
                    jo = new JSONObject(message);
                    final String fBase = jo.optString("FBase");
                    final String fWeight = jo.optString("FWeight");
                    String fBillNumber = jo.optString("FBillNumber");

                    currBillNumb = fBillNumber;
//                    mFbillNumberList.add(fBillNumber);

                    User currentUser = AppContext.getInstance().getCurrentUser();
                    if (currentUser == null) {
                        Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户为空，请重新登陆", Snackbar.LENGTH_SHORT).show();
                    } else {
                        handleOtherText(fBase, fWeight);
                    }
                } catch (JSONException e) {
                    Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描正确二维码!", Snackbar.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
            }
        }
    };

    private void handleOtherText(String text, String fWeight) {
        //先去判断扫描的单号是否存在
        boolean matExist = AddSale_Manager.getInstance(mActivity).isMatExist(text);
        if (matExist) {//存在
            onlyMatInsert(text, fWeight);
        } else {//不存在
            Snackbar.make(mActivity.getWindow().getDecorView(), "出库单不匹配，请重新扫描或同步数据！", Snackbar.LENGTH_SHORT).show();
        }
    }

    public int getHeight(View view) {// 获得某组件的高度
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        view.measure(w, h);
        return view.getMeasuredHeight();
    }

    //扫描条码只对应一个物料时的添加流程
    private void onlyMatInsert(String barcode, String fWeight) {

        //先判断已添加的中是否存在
        List<Add_bodyOut_Bean> listMatBean = mAdapter.getBackList();
        for (int i = 0; i < listMatBean.size(); i++) {
            Add_bodyOut_Bean addSyncBean = listMatBean.get(i);
            String id = addSyncBean.getFBillNum();
            //判断是否添加一样
            if (currBillNumb.equals(id)) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "请确认该产品是否已经添加！", Snackbar.LENGTH_SHORT).show();
                return;
            }
        }
        //设置数据
        Add_Sync_Bean matById = AddSale_Manager.getInstance(mActivity).getMatById(barcode);
        String model = matById.getModel();
        Add_bodyOut_Bean addSyncBean = new Add_bodyOut_Bean();

        addSyncBean.setUnit_id(matById.getUnit_id());
        addSyncBean.setId(matById.getId());
        addSyncBean.setCount(fWeight);
        addSyncBean.setModel(matById.getModel());
        addSyncBean.setName(matById.getName());
        addSyncBean.setNumber(matById.getNumber());
        addSyncBean.setUnitgroup_name(matById.getUnitgroup_name());
        addSyncBean.setUnit_name(matById.getUnit_name());
        addSyncBean.setDefunitId(matById.getDefunitId());
        addSyncBean.setBaseName(matById.getBaseName());
        addSyncBean.setBaseunit(matById.getBaseunit());
        addSyncBean.setUnitgroup_id(matById.getUnitgroup_id());
        addSyncBean.setFDCStockName(addSaleOut_HeadBean.getFDCStockIDName());
        addSyncBean.setFDCStockID(addSaleOut_HeadBean.getFDCStockID());
        addSyncBean.setFBillNum(currBillNumb);

//        BackMatManager.getInstance(mActivity).insertBackMat(backMatBean);//缓存
        checkedCKS.add(addSyncBean);

        count += Integer.parseInt(fWeight);
        tv_all.setText("" + count);


        TextView mTextView = new TextView(mActivity);
        mTextView.setTextSize(25);
        mTextView.setTextColor(Color.BLACK);
        mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
        int childCount = ll_content.getChildCount();
        boolean haseSame = false;
        int pos = -1;
        if (childCount == 0) {
            mTextView.setText(model + " 重量:" + fWeight);
            ll_content.addView(mTextView);
        } else {
            for (int i = 0; i < childCount; i++) {
                String s = ((TextView) ll_content.getChildAt(i)).getText().toString();
                if (s.contains(model)) {
//                ll_content.addView(mTextView);
                    pos = i;
                    haseSame = true;
                    break;
//                    ((TextView) ll_content.getChildAt(i)).setText(model + " zzz:" + fWeight);
                } else {
//                    mTextView.setText(model + " www:" + fWeight);
//                    ll_content.addView(mTextView);
                }
            }
            if (haseSame) {
                String text = ((TextView) ll_content.getChildAt(pos)).getText().toString();
                String substring = text.substring(text.indexOf(":") + 1, text.length());
                int i = Integer.parseInt(substring);
                int i1 = Integer.parseInt(fWeight);

                ((TextView) ll_content.getChildAt(pos)).setText(model + " 重量:" + (i + i1));
            } else {
                mTextView.setText(model + " 重量:" + fWeight);
                ll_content.addView(mTextView);
            }
        }


        mAdapter = new Add_Saleout_Adapter(mActivity, checkedCKS, this);
        mRecycleview.setAdapter(mAdapter);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                scrollView.fullScroll(ScrollView.FOCUS_DOWN);
            }
        });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = View.inflate(mActivity, R.layout.fragment_sale_out, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }


    @Override
    public void initView(View view) {
        super.initView(view);
        TDevice.hideSoftKeyboard(mActivity);
        setHasOptionsMenu(true);
        IntentFilter intentFilter = new IntentFilter(SCN_CUST_ACTION_SCODE);
        mActivity.registerReceiver(mSamDataReceiver, intentFilter);
        isSave = false;
        llGhUnit.setOnClickListener(this);
        llZdr.setOnClickListener(this);
        llBg.setOnClickListener(this);
        llYwy.setOnClickListener(this);
        llShWarehouse.setOnClickListener(this);
        llFh.setOnClickListener(this);
        checkedCKS = new ArrayList<>();

        FullyLinearLayoutManager linearLayoutManager = new FullyLinearLayoutManager(getContext());
        mRecycleview.setNestedScrollingEnabled(false);
        //设置布局管理器
        mRecycleview.setLayoutManager(linearLayoutManager);

        mAdapter = new Add_Saleout_Adapter(mActivity, checkedCKS, this);
    }

    @Override
    public void initData() {
        super.initData();
        mUser = AppContext.getInstance().getCurrentUser();
        addSaleOut_HeadBean = new AddSaleOut_HeadBean();
        //text
        String ADDSaleOuttvJhUnit = AppContext.getInstance().getProperty("ADDSaleOuttvJhUnit");
        String ADDSaleOuttvBg = AppContext.getInstance().getProperty("ADDSaleOuttvBg");
        String ADDSaleOuttvFh = AppContext.getInstance().getProperty("ADDSaleOuttvFh");
        String ADDSaleOuttvYwy = AppContext.getInstance().getProperty("ADDSaleOuttvYwy");
        String ADDSaleOuttvShWarehouse = AppContext.getInstance().getProperty("ADDSaleOuttvShWarehouse");

        //id
        String ADDSaleOuttvJhUnit_id = AppContext.getInstance().getProperty("ADDSaleOuttvJhUnit_id");
        String ADDSaleOuttvBg_id = AppContext.getInstance().getProperty("ADDSaleOuttvBg_id");
        String ADDSaleOuttvFh_id = AppContext.getInstance().getProperty("ADDSaleOuttvFh_id");
        String ADDSaleOuttvYwy_id = AppContext.getInstance().getProperty("ADDSaleOuttvYwy_id");
        String ADDSaleOuttvShWarehouse_id = AppContext.getInstance().getProperty("ADDSaleOuttvShWarehouse_id");

        if (!StringUtils.isEmpty(ADDSaleOuttvJhUnit) && !StringUtils.isEmpty(ADDSaleOuttvBg) && !StringUtils.isEmpty(ADDSaleOuttvFh)
                && !StringUtils.isEmpty(ADDSaleOuttvYwy) && !StringUtils.isEmpty(ADDSaleOuttvShWarehouse)) {

            tvGhUnit.setText(ADDSaleOuttvJhUnit);
            tvBg.setText(ADDSaleOuttvBg);
            tvFh.setText(ADDSaleOuttvFh);
            tvYwy.setText(ADDSaleOuttvYwy);
            tvShWarehouse.setText(ADDSaleOuttvShWarehouse);

            addSaleOut_HeadBean.setFSupplyID(ADDSaleOuttvJhUnit_id);
            addSaleOut_HeadBean.setFSupplyIDName(ADDSaleOuttvJhUnit);

            addSaleOut_HeadBean.setFBUser(ADDSaleOuttvBg_id);
            addSaleOut_HeadBean.setFBUserName(ADDSaleOuttvBg);

            addSaleOut_HeadBean.setFYUser(ADDSaleOuttvFh_id);
            addSaleOut_HeadBean.setFYUserName(ADDSaleOuttvFh);

            addSaleOut_HeadBean.setFPUser(ADDSaleOuttvYwy_id);
            addSaleOut_HeadBean.setFPUserName(ADDSaleOuttvYwy);

            addSaleOut_HeadBean.setFDCStockID(ADDSaleOuttvShWarehouse_id);
            addSaleOut_HeadBean.setFDCStockIDName(ADDSaleOuttvShWarehouse);
        }

        Bundle bundle = getArguments();
        mType = bundle.getString("TYPE");
        if ("show".equals(mType)) {

            String headid = bundle.getString("ID");
            long Id = Long.parseLong(headid);
            String count = AppContext.getInstance().getProperty(headid);
            tv_all.setText(count);

            List<String> environmentList = new ArrayList<String>();
            SharedPreferences preferDataList = mActivity.getSharedPreferences(headid, MODE_PRIVATE);
            int environNums = preferDataList.getInt("EnvironNums", 0);
            for (int i = 0; i < environNums; i++) {
                String environItem = preferDataList.getString("item_" + i, null);
                environmentList.add(environItem);
            }

            for (int i = 0; i < environmentList.size(); i++) {
                TextView mTextView = new TextView(mActivity);
                mTextView.setTextSize(25);
                mTextView.setTextColor(Color.BLACK);
                mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
                mTextView.setText(environmentList.get(i).toString());
                ll_content.addView(mTextView,i);
            }


            addSaleOut_HeadBean = AddSale_Manager.getInstance(mActivity).getHeadByIdout(Id + "");
            if (addSaleOut_HeadBean != null) {
                tvGhUnit.setText(addSaleOut_HeadBean.getFSupplyIDName());
                tvZdr.setText(addSaleOut_HeadBean.getFUserName());
                tvFh.setText(addSaleOut_HeadBean.getFYUserName());
                tvYwy.setText(addSaleOut_HeadBean.getFPUserName());
                tvBg.setText(addSaleOut_HeadBean.getFBUserName());
                tvShWarehouse.setText(addSaleOut_HeadBean.getFDCStockIDName());
            }
            List<Add_bodyOut_Bean> backMatsByHeadId = AddSale_Manager.getInstance(mActivity).getBackMatsByHeadIdout(Id);
            checkedCKS.addAll(backMatsByHeadId);

            mAdapter = new Add_Saleout_Adapter(mActivity, checkedCKS, this);
            mRecycleview.setAdapter(mAdapter);
        } else {
            mAdapter = new Add_Saleout_Adapter(mActivity, checkedCKS, this);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Bundle bundle = new Bundle();
        switch (v.getId()) {
            case R.id.ll_gh_unit:
                bundle.putString("type", "ghdw");
                UIHelper.showSimpleBackForResult(this, mActivity, 1, SimpleBackPage.CUST_PHEON, bundle, "购货单位");
                break;
            case R.id.ll_zdr:
                bundle.putString("type", "zdr");
                UIHelper.showSimpleBackForResult(this, mActivity, 2, SimpleBackPage.CUST_PHEON, bundle, "制单人");
                break;
            case R.id.ll_bg:
                bundle.putString("type", "bg");
                UIHelper.showSimpleBackForResult(this, mActivity, 3, SimpleBackPage.CUST_PHEON, bundle, "保管");
                break;
            case R.id.ll_fh:
                bundle.putString("type", "fh");
                UIHelper.showSimpleBackForResult(this, mActivity, 4, SimpleBackPage.CUST_PHEON, bundle, "发货");
                break;
            case R.id.ll_ywy:
                bundle.putString("type", "ywy");
                UIHelper.showSimpleBackForResult(this, mActivity, 5, SimpleBackPage.CUST_PHEON, bundle, "业务员");
                break;
            case R.id.ll_sh_warehouse:
                bundle.putString("type", "fhck");
                UIHelper.showSimpleBackForResult(this, mActivity, 6, SimpleBackPage.CUST_PHEON, bundle, "发货仓库");
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            final CustPhone item = (CustPhone) data.getSerializableExtra("item");
            if (item != null) {
                String name = item.getName();
                String id = item.getId();
                switch (requestCode) {
                    case 1:
                        tvGhUnit.setText(name);
                        addSaleOut_HeadBean.setFSupplyID(id);
                        addSaleOut_HeadBean.setFSupplyIDName(name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvJhUnit", name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvJhUnit_id", id);
                        break;
                    case 2:
                        tvZdr.setText(name);
                        break;
                    case 3:
                        tvBg.setText(name);
                        addSaleOut_HeadBean.setFBUser(id);
                        addSaleOut_HeadBean.setFBUserName(name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvBg", name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvBg_id", id);
                        break;
                    case 4:
                        tvFh.setText(name);
                        addSaleOut_HeadBean.setFYUser(id);
                        addSaleOut_HeadBean.setFYUserName(name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvFh", name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvFh_id", id);
                        break;
                    case 5:
                        tvYwy.setText(name);
                        addSaleOut_HeadBean.setFPUser(id);
                        addSaleOut_HeadBean.setFPUserName(name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvYwy", name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvYwy_id", id);
                        break;
                    case 6:
                        tvShWarehouse.setText(name);
                        addSaleOut_HeadBean.setFDCStockID(id);
                        addSaleOut_HeadBean.setFDCStockIDName(name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvShWarehouse", name);
                        AppContext.getInstance().setProperty("ADDSaleOuttvShWarehouse_id", id);
                        break;
                    case 7://adapter中点击发货仓库 自选的仓库
                        ArrayList<Add_bodyOut_Bean> backList = mAdapter.getBackList();
                        Add_bodyOut_Bean addSyncBean = backList.get(position);
                        addSyncBean.setTDCStockID(item.getId());
                        addSyncBean.setTDCStockName(item.getName());
                        backList.set(position, addSyncBean);
                        mAdapter.setBackList(backList);
                        mAdapter.notifyItemChanged(position);
                        break;
                }
            }
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_add_mat, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                subMat();
                break;
            case R.id.btn_save:
                saveMat();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //提交
    private void subMat() {
        List<String> environmentList = new ArrayList<String>();
//        SharedPreferences preferDataList = mActivity.getSharedPreferences("SALE_OUT", MODE_PRIVATE);
//        int environNums = preferDataList.getInt("EnvironNumsout", 0);
//        for (int i = 0; i < environNums; i++) {
//            String environItem = preferDataList.getString("itemout_" + i, null);
//            environmentList.add(environItem);
//        }

        ArrayList<Add_bodyOut_Bean> addSyncBeen_List = mAdapter.getBackList();
        if (addSyncBeen_List == null || addSyncBeen_List.size() == 0) {
            Snackbar.make(mActivity.getWindow().getDecorView(), "请扫描物料，再提交", Snackbar.LENGTH_SHORT).show();
            return;
        }

        for (int i = 0; i < addSyncBeen_List.size(); i++) {
            environmentList.add(addSyncBeen_List.get(i).getFBillNum());
        }

        //表头
        String fDSupplyID = addSaleOut_HeadBean.getFSupplyID();
        String fpUser = addSaleOut_HeadBean.getFPUser();
        String fyUser = addSaleOut_HeadBean.getFYUser();
        String fbUser = addSaleOut_HeadBean.getFBUser();
        String fdcStock = addSaleOut_HeadBean.getFDCStockID();

        if (mUser != null) {
            String id = mUser.getId();
            addSaleOut_HeadBean.setFUser(id);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "当前用户获取失败，请重新登陆！", Snackbar.LENGTH_SHORT).show();
        }

        if (!StringUtils.isEmpty(fDSupplyID) && !StringUtils.isEmpty(fdcStock) && !StringUtils.isEmpty(fbUser) && !StringUtils.isEmpty(fyUser)) {

            addSaleOut_HeadBean.setFSupplyID(fDSupplyID);
            addSaleOut_HeadBean.setFPUser(fpUser);
            addSaleOut_HeadBean.setFYUser(fyUser);
            addSaleOut_HeadBean.setFBUser(fbUser);
            addSaleOut_HeadBean.setFDCStockID(fdcStock);
            addSaleOut_HeadBean.setFtype("1");//1代表出库，-1是退货

            //表体
            List<AddSaleInt_bodyBean> bodys = new ArrayList<>();
            List<AddSaleInt_body_InOutList_Bean> bodyInOuts = new ArrayList<>();
            //判断列表进来
            if (environmentList != null && environmentList.size() > 0) {
                for (int i = 0; i < environmentList.size(); i++) {
                    AddSaleInt_body_InOutList_Bean bodyInOutsBean = new AddSaleInt_body_InOutList_Bean();
                    if (i == 0) {
                        bodyInOutsBean.setFCusId(fDSupplyID);
                    } else {
                    }
                    bodyInOutsBean.setFText(environmentList.get(i));
                    bodyInOuts.add(bodyInOutsBean);
                }
            }

            for (int i = 0; i < addSyncBeen_List.size(); i++) {
                AddSaleInt_bodyBean bodyBean = new AddSaleInt_bodyBean();
                Add_bodyOut_Bean addSyncBeans = addSyncBeen_List.get(i);

                String fCount = addSyncBeans.getCount();
                if (fCount.contains(".")) {
                    String counts = fCount.substring(0, fCount.indexOf("."));
                    bodyBean.setFQty(counts);
                } else {
                    bodyBean.setFQty(fCount);
                }
                String unit_id = addSyncBeans.getUnit_id();
                String fdcStockID = addSyncBeans.getTDCStockID();  //表体id
                String id = addSyncBeans.getId();

                if (!StringUtils.isEmpty(fdcStockID)) {
                    bodyBean.setFStockId(fdcStockID);
                } else if (!StringUtils.isEmpty(fdcStock)) {
                    bodyBean.setFStockId(fdcStock);
                } else {
                    bodyBean.setFStockId("0");
                }

                bodyBean.setFUnitId(unit_id);
                bodyBean.setFProductID(id);

                bodys.add(bodyBean);
            }

            showWaitDialog();
            AddSaleOut_HB_Bean addSaleIntHbBean = new AddSaleOut_HB_Bean();
            addSaleIntHbBean.setBodyList(bodys);
            addSaleIntHbBean.setInoutList(bodyInOuts);
            addSaleIntHbBean.setHeadDetail(addSaleOut_HeadBean);

            Gson gson = new Gson();
            String json = gson.toJson(addSaleIntHbBean);
            String token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
            CM cm = new CM();
            cm.setToken(token);
            cm.setData(json);
            RetrofitSingleton.getApiService(mActivity).
                    StockBillSubmit(cm)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(observer);
        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "必填信息不能为空！", Snackbar.LENGTH_SHORT).show();
        }
    }

    //保存
    private void saveMat() {

        ArrayList<Add_bodyOut_Bean> addSyncBeen_List = mAdapter.getBackList();
        int countList = 0;

        if (addSyncBeen_List != null && addSyncBeen_List.size() > 0) {
            for (int i = 0; i < addSyncBeen_List.size(); i++) {
                countList += Integer.parseInt(addSyncBeen_List.get(i).getCount());
            }
            addSaleOut_HeadBean.setUsername(AppContext.getInstance().getCurrentUser().getName());
            AddSale_Manager.getInstance(mActivity).inOrSale_Out(addSaleOut_HeadBean);
            AddSaleOut_HeadBean lastHead_saleout = AddSale_Manager.getInstance(mActivity).getLastHead_saleout();

            for (int i = 0; i < addSyncBeen_List.size(); i++) {
                addSyncBeen_List.get(i).setHeads(lastHead_saleout);
            }
            long headId = addSyncBeen_List.get(0).getHeadId();

            AppContext.getInstance().setProperty("" + headId, "" + countList);
            AddSale_Manager.getInstance(mActivity).insertBackMatsout(addSyncBeen_List);


            List<String> environmentList = new ArrayList<String>();
            int childCount = ll_content.getChildCount();
            for (int i = 0; i < childCount; i++) {
                String s = ((TextView) ll_content.getChildAt(i)).getText().toString();
                environmentList.add(s);
            }

            SharedPreferences.Editor editor = mActivity.getSharedPreferences("" + headId, MODE_PRIVATE).edit();
            editor.putInt("EnvironNums", environmentList.size());
            for (int i = 0; i < environmentList.size(); i++) {
                editor.putString("item_" + i, environmentList.get(i));
            }
            editor.commit();

//            SharedPreferences.Editor editor = mActivity.getSharedPreferences("SALE_OUT", MODE_PRIVATE).edit();
//            editor.putInt("EnvironNumsout", mFbillNumberList.size());
//            for (int i = 0; i < mFbillNumberList.size(); i++) {
//                editor.putString("itemout_" + i, mFbillNumberList.get(i));
//            }
//            editor.commit();

            Snackbar.make(mActivity.getWindow().getDecorView(), "保存成功!", Snackbar.LENGTH_SHORT).show();

            Intent intent = new Intent(AppConfig.SALE_OUT_SAVE);
            mActivity.sendBroadcast(intent);

            isSave = true;
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mActivity.finish();
                    Bundle bundle = new Bundle();
                    UIHelper.showSimpleBack(mActivity, SimpleBackPage.ADD_SALE_OUT, bundle, "销售出库");
                }
            }, 500);//3秒后执行Runnable中的run方法

        } else {
            Snackbar.make(mActivity.getWindow().getDecorView(), "未扫描单据不能保存!", Snackbar.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            mActivity.unregisterReceiver(mSamDataReceiver);
        } catch (Exception ex) {
        }
        ButterKnife.reset(this);
    }

    @Override
    public void onFHCKClick(Add_bodyOut_Bean bean, int position) {
        this.position = position;
        Bundle bundle = new Bundle();
        bundle.putString("type", "shck");
        UIHelper.showSimpleBackForResult(this, mActivity, 7, SimpleBackPage.CUST_PHEON, bundle, "收货仓库");
    }

    @Override
    public void onDeleted(Add_bodyOut_Bean bean, int position) {
        count -= Integer.parseInt(bean.getCount());
        tv_all.setText("" + count);


        int childCount = ll_content.getChildCount();
        if (childCount >0) {
            for (int i = 0; i < childCount; i++) {
                String s = ((TextView) ll_content.getChildAt(i)).getText().toString();
                if (s.contains(bean.getModel())) {

                    String text = ((TextView) ll_content.getChildAt(i)).getText().toString();
                    String substring = text.substring(text.indexOf(":") + 1, text.length());
                    int a = Integer.parseInt(substring);
                    int i1 = Integer.parseInt(bean.getCount());
                    if ((a-i1)==0){
                        ll_content.removeViewAt(i);
                    }else{
                        ((TextView) ll_content.getChildAt(i)).setText(bean.getModel() + " 重量:" + (a - i1));
                    }
                    break;
                }
            }
        }
    }

    @Override
    public void onDeleteCountClick(Add_bodyOut_Bean bean, int position) {
        this.position = position;
        String counts = bean.getCount();
        String s = tv_all.getText().toString();
        count = Integer.parseInt(s);
        count -= Integer.parseInt(counts);

        tv_all.setText("" + count);
    }

    @Override
    public void onDeleteClick(int position) {
        tv_all.setText("0");
    }

    Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            String errBody = ErrorHandler.handle(e);
            Snackbar.make(getActivity().getWindow().getDecorView(), errBody, Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result.isSuccess()) {
                Snackbar.make(mActivity.getWindow().getDecorView(), "提交成功!", Snackbar.LENGTH_SHORT).show();
                if ("show".equals(mType) || isSave) {
                    AddSale_Manager.getInstance(mActivity).delAllByIdOut(addSaleOut_HeadBean.getId());
                    AddSale_Manager.getInstance(mActivity).delAllByHeadIdOut(addSaleOut_HeadBean.getId());//提交成功后删除缓存
                }
                mActivity.finish();
            } else {
                Snackbar.make(mActivity.getWindow().getDecorView(), result.getMessage(), Snackbar.LENGTH_SHORT).show();
            }
        }
    };

}

